package org.adempiere.apps.graph;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.logging.Level;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import layout.TableLayout;

import org.compiere.apps.AEnv;
import org.compiere.apps.AWindow;
import org.compiere.apps.Waiting;
import org.compiere.apps.form.FormFrame;
import org.compiere.model.MBSCCard;
import org.compiere.model.MBSCCardLine;
import org.compiere.model.MBSCPerspective;
import org.compiere.model.MQuery;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

public class BSCCardPanelNew extends JPanel  implements MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2959083439029043253L;
	private JPanel totalPanel = new JPanel();
	private BSCCardLinePerspectivePanel[] perspectivePanels = null;
	private JPanel tableHeaderPanel = new JPanel();
	private MBSCCard card = null;
	private JLabel totalLabel = null;
	private JLabel statusLabel = null;
	private Dimension cardPanelDimension = null;
	
	private TableLayout tableLayout = null;
	private double[][] tableSize;
	
	private int num = 1;
	
	public BSCCardPanelNew(MBSCCard _card) {
		super();
		
		setBorder(BorderFactory.createLineBorder(Color.BLACK));
		addMouseListener(this);
		setCard(_card);
	}
	
	public BSCCardPanelNew(int BSC_Card_ID) {
		super();
	
		setBorder(BorderFactory.createLineBorder(Color.BLACK));
		addMouseListener(this);
		setBSC_Card_ID(BSC_Card_ID);
	}
	
	private void initLayout() {
		tableLayout = new TableLayout(initTableSize());
		setLayout(tableLayout);
	}
	
	private double[][] initTableSize() {
		int Size = 2 + (MBSCPerspective.getPerspective() != null ? MBSCPerspective.getPerspective().length : 0);
		Size = (Size < BSCTableHeaderPanel.tableHeader.length ? BSCTableHeaderPanel.tableHeader.length: Size);
		tableSize = new double[2][Size];
		for(int i = 0; i < Size; i++) {
			tableSize[0][i] = (i < Size ? getCellWidth(i) : 0);
			tableSize[1][i] = ( i < 2 ? BSCTableHeaderPanel.cellHeight[0] : getCellHeight(i));
		}
		return tableSize;
	}
	
	
	protected int getCellHeight(int i) {
		int result = 0;
		if (card != null && i > 1 && i - 2 < MBSCPerspective.getPerspective().length) {
			result = BSCTableHeaderPanel.cellHeight[0] ;
			result += card.getCardLinesFromPerspective().get(MBSCPerspective.getPerspective()[i-2].getBSC_Perspective_ID()).length * BSCCardLinePanel.cellHeight[0];
		}
		return result;
	}
	
	protected int getCellWidth(int i) {
		int result = 0;
		if (i == 0) {
			for(int j:BSCTableHeaderPanel.cellWidth) {
				result += j;
			}
		}
		return result;
	}
	
	public void initView() {
		setBorder(BorderFactory.createLineBorder(Color.BLACK));
		removeAll();
		initLayout();	
		num = 1;
		initPerspectives();
		cardPanelDimension = initDimesion();

		setSize(cardPanelDimension);
		setPreferredSize(cardPanelDimension);
		setMaximumSize(cardPanelDimension);
		setMinimumSize(cardPanelDimension);
		
		add(initTotalPanel(),"0,0");
		add(initTableHeaderPanel(),"0,1");
		
		if (perspectivePanels != null) {
			int i = 2;
			for(BSCCardLinePerspectivePanel panel: perspectivePanels) {
				String pos = "0,"+Integer.toString(i++);
				add(panel,pos);
			}
		}
		validate();
		repaint();
		updateUI();		
	}
	
	private Dimension initDimesion() {
		int width = 0;
		int height = 0;
		
		for(int i=0; i < tableSize[0].length; i++) {
			width += tableSize[0][i];
			height += tableSize[1][i];
		}
		
		cardPanelDimension = new Dimension(width+1,height+1);
		return cardPanelDimension;
	}

	public BSCCardLinePerspectivePanel[] initPerspectives() {
		if (getCard() != null) {
			if (MBSCPerspective.getPerspective() != null) {
				perspectivePanels = new BSCCardLinePerspectivePanel[MBSCPerspective.getPerspective().length];
				for(int i = 0; i < MBSCPerspective.getPerspective().length; i++) {
					int BSC_Perspective_ID = MBSCPerspective.getPerspective()[i].getBSC_Perspective_ID();
					perspectivePanels[i] = new BSCCardLinePerspectivePanel(BSC_Perspective_ID, card.getLinesFromPerspective(BSC_Perspective_ID),num);
					num = perspectivePanels[i].getNum();
					perspectivePanels[i].setBorder(getBorder());
				}
			}
		}
		return perspectivePanels;
	}
	
	public JPanel initTotalPanel() {
		totalPanel.removeAll();
		if (getCard() != null) {
			totalPanel = new JPanel();
			totalLabel = new JLabel("<html><u>"+getCard().getName()+"</u></html>");
			totalLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			totalLabel.setFont(getTotalFont());
			totalPanel.add(totalLabel);
			
			statusLabel = new JLabel("Статус исполнения");
			statusLabel.setFont(getTotalFont());
			statusLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			
			totalPanel.add(statusLabel);
			totalPanel.setBorder(getBorder());

			double value = (card == null ? 0 : card.getValueNumber().doubleValue() / 100);
			
			Color c;
			if (value > 0) c = Color.GREEN;
			else c = Color.RED;
			BSCPointPanel p = new BSCPointPanel(c);
			int size =  BSCTableHeaderPanel.cellHeight[0] / 3;
			Dimension d = new Dimension(size,size);
			p.setSize(d);
			p.setPreferredSize(d);
			p.setMaximumSize(d);
			p.setMinimumSize(d);
			totalPanel.add(p);
		}
		return totalPanel;
	}

	public MBSCCard getCard() {
		return card;
	}

	public void setCard(MBSCCard card) {
		this.card = card;
		initView();
	}

	public int getBSC_Card_ID() {
		return (card != null ? card.getBSC_Card_ID() : 0);
	}
	
	public void setBSC_Card_ID(int BSC_Card_ID) {
		if (BSC_Card_ID > 0)
			setCard(new MBSCCard(Env.getCtx(),BSC_Card_ID,null));
		else
			card = null;
	}
	
	public static Font getTotalFont() {
		Font result = new Font("Times New Roman",Font.BOLD,14);
		
		return result;
	}
	
	private JPanel initTableHeaderPanel() {
		tableHeaderPanel = new BSCTableHeaderPanel();
		
		return tableHeaderPanel;
	}

	/**
	 * 
	 */
	private void openCardWindow() {
		totalLabel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		AWindow myWindow = new AWindow(getGraphicsConfiguration());
		int AD_Window_ID = getBSC_CardWindow_ID();
		MQuery query = new MQuery(MBSCCard.Table_ID);
		query.addRestriction("BSC_Card_ID", MQuery.EQUAL, card.getBSC_Card_ID());
		
		if (myWindow.initWindow(AD_Window_ID, query)) {
			AEnv.addToWindowManager(myWindow);
			myWindow.pack();
			myWindow.setVisible(true);
			myWindow.toFront();
		};
		totalLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	}
	
	public static int getBSC_CardWindow_ID() {
		int result = 0;
		String sql = "SELECT * FROM AD_Window WHERE Name like 'BSC_Card'";
		result = DB.getSQLValue(null, sql);
		return result;
	}

	private boolean isTitle(MouseEvent e) {
		int y = totalPanel.getY();
		int x = statusLabel.getX() - 10;
		int height = totalPanel.getHeight();
		
		boolean result = (y < e.getY() && e.getY() < y + height && e.getX() < x);
		
		return result;
	}
	
	/**
	 * @param e
	 * @return
	 */
	private boolean isTitleThermometer(MouseEvent e) {
		int y = totalPanel.getY();
		int x = statusLabel.getX() - 10;
		int height = totalPanel.getHeight();
		
		boolean result = (y < e.getY() && e.getY() < y + height && x < e.getX());
		return result;
	}
	
	private void openBarChartWindow(int BSC_Card_ID) {
		statusLabel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		if(BSC_Card_ID > 0) {
			FormFrame myWindow = new FormFrame(Env.getWindow(0).getGraphicsConfiguration());
			if (myWindow.openForm(getBSCViewBarChart())) {
				BSCViewBarChart view = (BSCViewBarChart) myWindow.getFormPanel();
				view.setBSC_Card_ID(BSC_Card_ID);
				AEnv.addToWindowManager(myWindow);
				AEnv.showCenterScreen(myWindow);
				myWindow.setVisible(true);
				myWindow.setFocusableWindowState(true);
				myWindow.toFront();
			}			
		}
		statusLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	}

	public static int getBSCViewBarChart() {
		int result = 0;
		String sql = "SELECT AD_Form_ID FROM AD_Form WHERE Name like 'BSCViewBarChart'";
		result = DB.getSQLValue(null, sql);
		return result;
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (isTitle(e) && card != null) {
			openCardWindow();
		} else if(isTitleThermometer(e) && card != null) {
			openBarChartWindow(card.getBSC_Card_ID());
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
}
